from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.models import AbstractUser
from django.db import models
from common.db import DbModel
# Create your models here.

class Users(AbstractUser):
    """定义用户信息模型"""
    phone_number =models.CharField(max_length=11,  verbose_name='手机号')
    avatar = models.ImageField(verbose_name='用户头像', blank=True, null=True)
    email = models.EmailField(verbose_name='邮箱地址', unique=True)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    class Meta:
        db_table = 'users'
        verbose_name = '用户信息表'

    def __str__(self):
        return self.username

class Addr( DbModel):
    """定义用户地址模型表"""
    user = models.ForeignKey(Users, on_delete=models.CASCADE, verbose_name="所属用户")
    re_name = models.CharField(max_length=100, verbose_name='收货人')
    province = models.CharField(max_length=100, verbose_name='省份')
    city = models.CharField(max_length=100, verbose_name='市')
    district = models.CharField(max_length=100, verbose_name='区/县')
    address_detail = models.CharField(max_length=255, verbose_name='详细地址')
    re_phone = models.CharField(max_length=11, verbose_name='收货人手机号')
    is_default = models.BooleanField(verbose_name='是否设为默认地址', default=False)

    class Meta:
        db_table = 'address'
        verbose_name = '收获地址信息'

    def __str__(self):
        return f"{self.re_name} - {self.district}, {self.city}"

class VerifyCode( models.Model):
    code = models.CharField(max_length=10, verbose_name='验证码')
    expiration = models.DateTimeField(verbose_name='验证码过期时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='验证码创建时间')
    mobile = models.CharField(max_length=11, verbose_name='发送验证码的手机号')
    is_used = models.BooleanField(default=False, verbose_name='验证码是否已经被使用')
    class Meta:
        db_table = 'verifyCode'
        verbose_name = '验证码表'
    def save(self, *args, **kwargs):
        if not self.expiration:
            self.expiration = timezone.now() + timedelta(minutes=10)
            super().save(*args, **kwargs)
    def __str__(self):
        return f'{self.code},验证码是否已过期：{self.is_used}'